{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Display Table of Food Orders in a Restaurant"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #array #hash-table #string #ordered-set #sorting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #数组 #哈希表 #字符串 #有序集合 #排序"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: displayTable"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #点菜展示表"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>给你一个数组 <code>orders</code>，表示客户在餐厅中完成的订单，确切地说， <code>orders[i]=[customerName<sub>i</sub>,tableNumber<sub>i</sub>,foodItem<sub>i</sub>]</code> ，其中 <code>customerName<sub>i</sub></code> 是客户的姓名，<code>tableNumber<sub>i</sub></code> 是客户所在餐桌的桌号，而 <code>foodItem<sub>i</sub></code> 是客户点的餐品名称。</p>\n",
    "\n",
    "<p>请你返回该餐厅的 <strong>点菜展示表</strong><em> 。</em>在这张表中，表中第一行为标题，其第一列为餐桌桌号 &ldquo;Table&rdquo; ，后面每一列都是按字母顺序排列的餐品名称。接下来每一行中的项则表示每张餐桌订购的相应餐品数量，第一列应当填对应的桌号，后面依次填写下单的餐品数量。</p>\n",
    "\n",
    "<p>注意：客户姓名不是点菜展示表的一部分。此外，表中的数据行应该按餐桌桌号升序排列。</p>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>示例 1：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>orders = [[&quot;David&quot;,&quot;3&quot;,&quot;Ceviche&quot;],[&quot;Corina&quot;,&quot;10&quot;,&quot;Beef Burrito&quot;],[&quot;David&quot;,&quot;3&quot;,&quot;Fried Chicken&quot;],[&quot;Carla&quot;,&quot;5&quot;,&quot;Water&quot;],[&quot;Carla&quot;,&quot;5&quot;,&quot;Ceviche&quot;],[&quot;Rous&quot;,&quot;3&quot;,&quot;Ceviche&quot;]]\n",
    "<strong>输出：</strong>[[&quot;Table&quot;,&quot;Beef Burrito&quot;,&quot;Ceviche&quot;,&quot;Fried Chicken&quot;,&quot;Water&quot;],[&quot;3&quot;,&quot;0&quot;,&quot;2&quot;,&quot;1&quot;,&quot;0&quot;],[&quot;5&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;],[&quot;10&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;]] \n",
    "<strong>解释：\n",
    "</strong>点菜展示表如下所示：\n",
    "<strong>Table,Beef Burrito,Ceviche,Fried Chicken,Water</strong>\n",
    "3    ,0           ,2      ,1            ,0\n",
    "5    ,0           ,1      ,0            ,1\n",
    "10   ,1           ,0      ,0            ,0\n",
    "对于餐桌 3：David 点了 &quot;Ceviche&quot; 和 &quot;Fried Chicken&quot;，而 Rous 点了 &quot;Ceviche&quot;\n",
    "而餐桌 5：Carla 点了 &quot;Water&quot; 和 &quot;Ceviche&quot;\n",
    "餐桌 10：Corina 点了 &quot;Beef Burrito&quot; \n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 2：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>orders = [[&quot;James&quot;,&quot;12&quot;,&quot;Fried Chicken&quot;],[&quot;Ratesh&quot;,&quot;12&quot;,&quot;Fried Chicken&quot;],[&quot;Amadeus&quot;,&quot;12&quot;,&quot;Fried Chicken&quot;],[&quot;Adam&quot;,&quot;1&quot;,&quot;Canadian Waffles&quot;],[&quot;Brianna&quot;,&quot;1&quot;,&quot;Canadian Waffles&quot;]]\n",
    "<strong>输出：</strong>[[&quot;Table&quot;,&quot;Canadian Waffles&quot;,&quot;Fried Chicken&quot;],[&quot;1&quot;,&quot;2&quot;,&quot;0&quot;],[&quot;12&quot;,&quot;0&quot;,&quot;3&quot;]] \n",
    "<strong>解释：</strong>\n",
    "对于餐桌 1：Adam 和 Brianna 都点了 &quot;Canadian Waffles&quot;\n",
    "而餐桌 12：James, Ratesh 和 Amadeus 都点了 &quot;Fried Chicken&quot;\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 3：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>orders = [[&quot;Laura&quot;,&quot;2&quot;,&quot;Bean Burrito&quot;],[&quot;Jhon&quot;,&quot;2&quot;,&quot;Beef Burrito&quot;],[&quot;Melissa&quot;,&quot;2&quot;,&quot;Soda&quot;]]\n",
    "<strong>输出：</strong>[[&quot;Table&quot;,&quot;Bean Burrito&quot;,&quot;Beef Burrito&quot;,&quot;Soda&quot;],[&quot;2&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;]]\n",
    "</pre>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>1 &lt;=&nbsp;orders.length &lt;= 5 * 10^4</code></li>\n",
    "\t<li><code>orders[i].length == 3</code></li>\n",
    "\t<li><code>1 &lt;= customerName<sub>i</sub>.length, foodItem<sub>i</sub>.length &lt;= 20</code></li>\n",
    "\t<li><code>customerName<sub>i</sub></code> 和 <code>foodItem<sub>i</sub></code> 由大小写英文字母及空格字符 <code>&#39; &#39;</code> 组成。</li>\n",
    "\t<li><code>tableNumber<sub>i</sub></code> 是 <code>1</code> 到 <code>500</code> 范围内的整数。</li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [display-table-of-food-orders-in-a-restaurant](https://leetcode.cn/problems/display-table-of-food-orders-in-a-restaurant/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [display-table-of-food-orders-in-a-restaurant](https://leetcode.cn/problems/display-table-of-food-orders-in-a-restaurant/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['[[\"David\",\"3\",\"Ceviche\"],[\"Corina\",\"10\",\"Beef Burrito\"],[\"David\",\"3\",\"Fried Chicken\"],[\"Carla\",\"5\",\"Water\"],[\"Carla\",\"5\",\"Ceviche\"],[\"Rous\",\"3\",\"Ceviche\"]]', '[[\"James\",\"12\",\"Fried Chicken\"],[\"Ratesh\",\"12\",\"Fried Chicken\"],[\"Amadeus\",\"12\",\"Fried Chicken\"],[\"Adam\",\"1\",\"Canadian Waffles\"],[\"Brianna\",\"1\",\"Canadian Waffles\"]]', '[[\"Laura\",\"2\",\"Bean Burrito\"],[\"Jhon\",\"2\",\"Beef Burrito\"],[\"Melissa\",\"2\",\"Soda\"]]']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from sortedcontainers import SortedDict\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        # 转换orders为，所有订单里的全部桌和全部食物\n",
    "        obj = list(zip(*orders))\n",
    "        # 排序好的tables，每个table对应结果数组中的第几行\n",
    "        tables = SortedDict({v:i for i,v in enumerate(sorted(map(int,set(obj[1]))), 1)})\n",
    "        # 排序好的foods，每个food对应结果数组中的第几列\n",
    "        foods = SortedDict({v:i for i,v in enumerate(sorted(set(obj[2])), 1)})\n",
    "        # 生成结果数组并填好第一行第一列\n",
    "        res = [[\"Table\"] + [food for food in foods]] + [[str(key)] + [\"0\"] * len(foods) for key in tables]\n",
    "        # 统计每桌每个食物的数量\n",
    "        for _, table, food in orders:\n",
    "            res[tables[int(table)]][foods[food]] = str(int(res[tables[int(table)]][foods[food]]) + 1)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        r=set()\n",
    "        n=set()\n",
    "        for k in orders:\n",
    "            r.add(int(k[1]))\n",
    "            n.add(k[2])\n",
    "\n",
    "        n=list(n)\n",
    "        n.sort()\n",
    "        r=list(r)\n",
    "        r.sort()\n",
    "        w=[[\"Table\"]+n]\n",
    "\n",
    "        dn=dict()\n",
    "        p=1\n",
    "        for x in n:\n",
    "            dn[x]=p\n",
    "            p+=1\n",
    "        dr=dict()\n",
    "        q=1\n",
    "        for x in r:\n",
    "            dr[x]=q\n",
    "            q+=1\n",
    "\n",
    "        for i in r:\n",
    "            w.append([str(i)]+[\"0\" for j in range(len(n))])\n",
    "        for k in orders:\n",
    "            w[dr[int(k[1])]][dn[k[2]]]=str(int(w[dr[int(k[1])]][dn[k[2]]])+1)\n",
    "        return w\n",
    "            \n",
    "        \n",
    "        \n",
    "        \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import defaultdict\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        d = dict()\n",
    "        a = list()\n",
    "        for temp in orders:\n",
    "            table = int(temp[1])\n",
    "            if table not in d:\n",
    "\n",
    "                d[table] = {}\n",
    "            if temp[2] not in d[table]:\n",
    "                d[table][temp[2]] = 0\n",
    "            if temp[2] not in a:\n",
    "                a.append(temp[2])\n",
    "            d[table][temp[2]] += 1\n",
    "        a.sort()\n",
    "        a.insert(0, \"Table\")\n",
    "        z = list()\n",
    "        z.append(a)\n",
    "        for key in sorted(d.keys()):\n",
    "            value = d[key]\n",
    "            temp = [str(key)]\n",
    "            for i in a[1:]:\n",
    "                if i in value.keys():\n",
    "                    temp.append(str(value[i]))\n",
    "                else:\n",
    "                    temp.append(\"0\")\n",
    "            z.append(temp)\n",
    "        return z"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        food_list = set()\n",
    "        table_food_cnt = defaultdict(dict)\n",
    "        for order in orders:\n",
    "            food_list.add(order[2])\n",
    "            if order[2] not in table_food_cnt[int(order[1])]:\n",
    "                table_food_cnt[int(order[1])][order[2]] = 1\n",
    "            else:\n",
    "                table_food_cnt[int(order[1])][order[2]] += 1\n",
    "\n",
    "        result = [['Table'] + list(sorted(food_list))]\n",
    "        for table in sorted(table_food_cnt.keys()):\n",
    "            table_food = [str(table)]\n",
    "            for key in result[0][1:]:\n",
    "                if key in table_food_cnt[table]:\n",
    "                    table_food.append(str(table_food_cnt[table][key]))\n",
    "                else:\n",
    "                    table_food.append('0')\n",
    "            result.append(table_food)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        res = {}\n",
    "        caidan = []\n",
    "        result = []\n",
    "        for dd in orders:\n",
    "            if dd[2] not in caidan:\n",
    "                caidan.append(dd[2])\n",
    "            if dd[1] not in res:\n",
    "                res[dd[1]] = {}\n",
    "            if dd[2] in res[dd[1]]:\n",
    "                res[dd[1]][dd[2]] += 1\n",
    "            else:\n",
    "                res[dd[1]][dd[2]] = 1\n",
    "        caidan.sort()\n",
    "        caidan.insert(0,\"Table\")\n",
    "        result.append(caidan)\n",
    "\n",
    "        res_data = {int(k):v for k,v in res.items()}\n",
    "        res_data = dict(sorted(res_data.items()))\n",
    "        res_data = {str(k):v for k,v in res_data.items()}\n",
    "\n",
    "        for k,v in res_data.items():\n",
    "            da = []\n",
    "            da.append(k)\n",
    "\n",
    "            for a in caidan[1:]:\n",
    "        \n",
    "                if a in v:\n",
    "\n",
    "                    da.append(str(v[a]))\n",
    "                else:\n",
    "                    da.append('0')\n",
    "            result.append(da)\n",
    "\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders):\n",
    "        foodItem=[]\n",
    "        tableNumber=[]\n",
    "        l=[]\n",
    "        for i in orders:\n",
    "            foodItem.append(i[2])\n",
    "        foodItem=list(set(foodItem))\n",
    "        foodItem.sort()\n",
    "        for i in orders:\n",
    "            tableNumber.append(i[1])\n",
    "        tableNumber=[int(i) for i in list(set(tableNumber))]\n",
    "        tableNumber.sort()\n",
    "        tableNumber = [str(i) for i in tableNumber]\n",
    "\n",
    "        for i in tableNumber:\n",
    "            order=[i]\n",
    "            for j in range(len(foodItem)):\n",
    "                order.append(\"0\")\n",
    "            l.append(order)\n",
    "        for i in orders:\n",
    "            for j in range(len(l)):\n",
    "                if i[1]==l[j][0]:\n",
    "                    l[j][foodItem.index(i[2]) + 1]=str(int(l[j][foodItem.index(i[2]) + 1]) + 1)\n",
    "        title=[i for i in foodItem]\n",
    "        title.insert(0,\"Table\")\n",
    "        l.insert(0, title)\n",
    "        return l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        ans = []\n",
    "        title = set()\n",
    "        customer = defaultdict(defaultdict)\n",
    "        for name,id,food in orders:\n",
    "            if food not in title:\n",
    "                title.add(food)\n",
    "            customer[id][food] =  customer[id].get(food,0)+1\n",
    "        ls = list(title)\n",
    "        ls.sort()\n",
    "        #构建一个排序后食物-id对应表\n",
    "        dic = {}\n",
    "        n = len(ls)\n",
    "        for i,food in enumerate(ls):\n",
    "            dic[food] = i+1\n",
    "        #构建所有的餐桌对应的菜品数量\n",
    "        ls = [\"Table\"]+ls\n",
    "        for key,val in customer.items():\n",
    "            temp = [\"0\"]*(n+1)\n",
    "            temp[0] = key\n",
    "            for food,num in val.items():\n",
    "                temp[dic[food]] = str(num)\n",
    "            ans.append(temp)\n",
    "        ans.sort(key = lambda x:int(x[0]))\n",
    "        ans = [ls]+ans\n",
    "        return ans\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders):\n",
    "        foodItem=[]\n",
    "        tableNumber=[]\n",
    "        l=[]\n",
    "        for i in orders:\n",
    "            foodItem.append(i[2])\n",
    "            tableNumber.append(i[1])\n",
    "        tableNumber=[int(i) for i in list(set(tableNumber))]\n",
    "        tableNumber.sort()\n",
    "        tableNumber = [str(i) for i in tableNumber]\n",
    "        foodItem=list(set(foodItem))\n",
    "        foodItem.sort()\n",
    "\n",
    "        for i in tableNumber:\n",
    "            order=[i]\n",
    "            for j in range(len(foodItem)):\n",
    "                order.append(\"0\")\n",
    "            l.append(order)\n",
    "        for i in orders:\n",
    "            for j in range(len(l)):\n",
    "                if i[1]==l[j][0]:\n",
    "                    l[j][foodItem.index(i[2]) + 1]=str(int(l[j][foodItem.index(i[2]) + 1]) + 1)\n",
    "        title=[i for i in foodItem]\n",
    "        title.insert(0,\"Table\")\n",
    "        l.insert(0, title)\n",
    "        return l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        food_list = set()\n",
    "        table_food_cnt = defaultdict(dict)\n",
    "        for order in orders:\n",
    "            food_list.add(order[2])\n",
    "            if order[2] not in table_food_cnt[int(order[1])]:\n",
    "                table_food_cnt[int(order[1])][order[2]] = 1\n",
    "            else:\n",
    "                table_food_cnt[int(order[1])][order[2]] += 1\n",
    "\n",
    "        result = [['Table'] + list(sorted(food_list))]\n",
    "        for table in sorted(table_food_cnt.keys()):\n",
    "            table_food = [str(table)]\n",
    "            for key in result[0][1:]:\n",
    "                if key in table_food_cnt[table]:\n",
    "                    table_food.append(str(table_food_cnt[table][key]))\n",
    "                else:\n",
    "                    table_food.append('0')\n",
    "            result.append(table_food)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        # orders   【姓名、桌号、餐品名称】\n",
    "        # 返回值  餐桌号Table | 按照字母顺序排序的餐品名称 | \n",
    "        # 结果列表 |\n",
    "        # {\"桌号\":{\"菜1\":1,\"菜2\":2}}\n",
    "        res = {}\n",
    "        # 需要一个菜单列表\n",
    "        caidan = []\n",
    "        result = []\n",
    "        for dd in orders:\n",
    "            if dd[2] not in caidan:\n",
    "                caidan.append(dd[2])\n",
    "            if dd[1] not in res:\n",
    "                res[dd[1]] = {}\n",
    "            if dd[2] in res[dd[1]]:\n",
    "                res[dd[1]][dd[2]] += 1\n",
    "            else:\n",
    "                res[dd[1]][dd[2]] = 1\n",
    "\n",
    "            # res[dd[1]] = {dd[2]:1}\n",
    "            # print(dd)\n",
    "        caidan.sort()\n",
    "        caidan.insert(0,\"Table\")\n",
    "        result.append(caidan)\n",
    "\n",
    "        # print(caidan)\n",
    "        # print(res)\n",
    "        # 答案的解析\n",
    "        # 对字典进行排序\n",
    "        res_data = {int(k):v for k,v in res.items()}\n",
    "        res_data = dict(sorted(res_data.items()))\n",
    "        res_data = {str(k):v for k,v in res_data.items()}\n",
    "        # print(res_data)\n",
    "        # 处理列表 【】\n",
    "        for k,v in res_data.items():\n",
    "            da = []\n",
    "            da.append(k)\n",
    "            print(\"k=\",k)\n",
    "            print(\"v=\",v)\n",
    "            for a in caidan[1:]:\n",
    "                print(\"a=\",a)           \n",
    "                if a in v:\n",
    "                    # print(v[a])\n",
    "                    da.append(str(v[a]))\n",
    "                else:\n",
    "                    da.append('0')\n",
    "            result.append(da)\n",
    "        # print(result)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\r\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\r\n",
    "        #[[\"David\",\"3\",\"Ceviche\"],\r\n",
    "        # [\"Corina\",\"10\",\"Beef Burrito\"],\r\n",
    "        # [\"David\",\"3\",\"Fried Chicken\"],\r\n",
    "        # [\"Carla\",\"5\",\"Water\"],\r\n",
    "        # [\"Carla\",\"5\",\"Ceviche\"],\r\n",
    "        # [\"Rous\",\"3\",\"Ceviche\"]]\r\n",
    "        \r\n",
    "        #[[\"Table\",\"Beef Burrito\",\"Ceviche\",\"Fried Chicken\",\"Water\"]\r\n",
    "        # ,[\"3\",\"0\",\"2\",\"1\",\"0\"],\r\n",
    "        # [\"5\",\"0\",\"1\",\"0\",\"1\"]\r\n",
    "        # ,[\"10\",\"1\",\"0\",\"0\",\"0\"]]\r\n",
    "\r\n",
    "        #table上的菜名字典序，桌子号升序\r\n",
    "        meal = set()\r\n",
    "        table = set()\r\n",
    "        for order in orders:\r\n",
    "            meal.add(order[2])\r\n",
    "            table.add(order[1])\r\n",
    "        meal = sorted(meal)\r\n",
    "        table = sorted(table, key=lambda x:int(x))\r\n",
    "        #统计每个桌子上的菜品数量\r\n",
    "        table_meal = {}\r\n",
    "        for order in orders:\r\n",
    "            if order[1] not in table_meal:\r\n",
    "                table_meal[order[1]] = {}\r\n",
    "            if order[2] not in table_meal[order[1]]:\r\n",
    "                table_meal[order[1]][order[2]] = 0\r\n",
    "            table_meal[order[1]][order[2]] += 1\r\n",
    "        res = [[\"Table\"] + meal]\r\n",
    "        for t in table:\r\n",
    "            tmp = [t]\r\n",
    "            for m in meal:\r\n",
    "                if m in table_meal[t]:\r\n",
    "                    tmp.append(str(table_meal[t][m]))\r\n",
    "                else:\r\n",
    "                    tmp.append(\"0\")\r\n",
    "            res.append(tmp)\r\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        record = {}\n",
    "        foods = set()\n",
    "        for customer, table, food in orders:\n",
    "            if table not in record:\n",
    "                record[table] = {}\n",
    "                record[table][food] = [customer]\n",
    "            else:\n",
    "                if food not in record[table]:\n",
    "                    record[table][food] = [customer]\n",
    "                else:\n",
    "                    record[table][food] += [customer]\n",
    "            foods.add(food)\n",
    "        # print(record)\n",
    "        res = []\n",
    "        temp = ['Table'] + sorted([food for food in foods])\n",
    "        # print(temp)\n",
    "        res.append(temp)\n",
    "        table = sorted(record.keys(), key=lambda x:int(x))\n",
    "        # print(table)\n",
    "        for t in table:\n",
    "            cur = [t]\n",
    "            for food in temp[1:]:\n",
    "                if food not in record[t]:\n",
    "                    cur.append('0')\n",
    "                else:\n",
    "                    cur.append(str(len(record[t][food])))\n",
    "            res.append(cur)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        foodItems = set()\n",
    "        tableFoodItems = {}\n",
    "        for i in range(len(orders)):\n",
    "            tableNumber = orders[i][1]\n",
    "            foodItem = orders[i][2]\n",
    "            foodItems.add(foodItem)\n",
    "            if tableNumber not in tableFoodItems:\n",
    "                tableFoodItems[tableNumber] = {\n",
    "\t\t\t\t\tfoodItem: 1\n",
    "\t\t\t\t}\n",
    "            elif foodItem not in tableFoodItems[tableNumber]:\n",
    "                tableFoodItems[tableNumber][foodItem] = 1\n",
    "            else:\n",
    "                tableFoodItems[tableNumber][foodItem] += 1\n",
    "        contents = []\n",
    "        title = [\"Table\"]\n",
    "        title.extend(sorted(list(foodItems)))\n",
    "        for tableNumber, foodItemCount in tableFoodItems.items():\n",
    "            content = [tableNumber]\n",
    "            for foodItem in title[1:]:\n",
    "                content.append(str(foodItemCount[foodItem]) if foodItem in foodItemCount else \"0\")\n",
    "            contents.append(content)\n",
    "        contents = sorted(contents, key=lambda x: int(x[0]))\n",
    "        ans = []\n",
    "        ans.append(title)\n",
    "        ans.extend(contents)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        ans = {}\n",
    "        fo = []\n",
    "        ind = []\n",
    "        for ord in orders:\n",
    "            tab = ord[1]\n",
    "            food = ord[2]\n",
    "            if tab not in ind:\n",
    "                ind.append(tab)\n",
    "            if food not in fo:\n",
    "                fo.append(food)\n",
    "            if tab not in ans:\n",
    "                ans[tab] = {}\n",
    "                ans[tab][food] = 1\n",
    "            else:\n",
    "                if food not in ans[tab]:\n",
    "                    ans[tab][food] = 1\n",
    "                else:\n",
    "                    ans[tab][food] = ans[tab][food] + 1\n",
    "        fo = sorted(fo)\n",
    "        ind = sorted(ind,key = lambda x:int(x))\n",
    "        res = []\n",
    "        first = []\n",
    "        first.append(\"Table\")\n",
    "        for f in fo:\n",
    "            first.append(f)\n",
    "        res.append(first)\n",
    "        for i in ind:\n",
    "            second = []\n",
    "            second.append(i)\n",
    "            for f in fo:\n",
    "                if f not in ans[i]:\n",
    "                    second.append(\"0\")\n",
    "                else:\n",
    "                    second.append(str(ans[i][f]))\n",
    "            res.append(second)\n",
    "        return res\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        ans = []\n",
    "        delicacies = []\n",
    "        for i in orders:\n",
    "            if i[2] not in delicacies:\n",
    "                delicacies.append(i[2])\n",
    "        delicacies.sort()\n",
    "        delicacies.insert(0,\"Table\")\n",
    "        ans.append(delicacies)\n",
    "        tmp = {x:i for i,x in enumerate(delicacies)}\n",
    "        mydict = {}\n",
    "        for i in orders:\n",
    "            if i[1] not in mydict.keys():\n",
    "                mydict[i[1]] = [\"0\"] * (len(delicacies) - 1)\n",
    "                mydict[i[1]][tmp[i[2]]-1] = \"1\"\n",
    "            else :\n",
    "                mydict[i[1]][tmp[i[2]]-1] = str(int(mydict[i[1]][tmp[i[2]]-1]) + 1)\n",
    "        mydict = sorted(mydict.items(),key=lambda x:int(x[0]))\n",
    "        for i in mydict:\n",
    "            c = i[1]\n",
    "            c.insert(0,i[0])\n",
    "            ans.append(c)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        table=[]\n",
    "        if orders is None or len(orders)==0:\n",
    "            return table\n",
    "        foodItems=[]\n",
    "        tableNumbers=[]\n",
    "        foodCountForEachTable={}\n",
    "        for other in orders:\n",
    "            tableNumber=int(other[1])\n",
    "            food=other[2]\n",
    "            tableNumbers.append(tableNumber)\n",
    "            foodItems.append(food)\n",
    "            foodForEachTable=foodCountForEachTable.get(tableNumber,{})\n",
    "            foodForEachTable[food]=foodForEachTable.get(food,0)+1\n",
    "            foodCountForEachTable[tableNumber]=foodForEachTable\n",
    "        foodList=list(set(foodItems))\n",
    "        foodList.sort()\n",
    "        tableList=list(set(tableNumbers))\n",
    "        tableList.sort()\n",
    "        header=[]\n",
    "        header.append(\"Table\")\n",
    "        header.extend(foodList)\n",
    "        table.append(header)\n",
    "        for tableNumber in tableList:\n",
    "            row=[]\n",
    "            row.append(str(tableNumber))\n",
    "            foodCount=foodCountForEachTable.get(tableNumber)\n",
    "            for food in foodList:\n",
    "                count=foodCount.get(food,0)\n",
    "                row.append(str(count))\n",
    "            table.append(row[:])\n",
    "        return table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        all_food = set()\n",
    "        stat = defaultdict(Counter)\n",
    "        for _, table, food in orders:\n",
    "            stat[table][food] += 1\n",
    "            all_food.add(food)\n",
    "\n",
    "        all_food = sorted(all_food)\n",
    "        ans = [['Table'] + all_food]\n",
    "        for table in sorted(stat, key=int):\n",
    "            cnt = stat[table]\n",
    "            l = [table] + [str(cnt[f]) for f in all_food]\n",
    "            ans.append(l)\n",
    "        \n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        res = []\n",
    "        \n",
    "        foods = set()\n",
    "        tables = set()\n",
    "        for _, t, food in orders:\n",
    "            tables.add(int(t))\n",
    "            foods.add(food)\n",
    "        foods = sorted(list(foods))\n",
    "        tables = [str(i) for i in sorted(list(tables))]\n",
    "        \n",
    "        res.append([\"Table\"] + foods)\n",
    "        \n",
    "        record = {}\n",
    "        for _, t, f in orders:\n",
    "            if t not in record:\n",
    "                record[t] = {}\n",
    "            if f not in record[t]:\n",
    "                record[t][f] = 0\n",
    "            record[t][f] += 1\n",
    "        \n",
    "        for t in tables:\n",
    "            col = [t]\n",
    "            for f in foods:\n",
    "                col.append(str(record[t].get(f, 0)))\n",
    "            res.append(col)\n",
    "        \n",
    "        return res\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        all_food = set()\n",
    "        stat = defaultdict(Counter)\n",
    "        for _, table, food in orders:\n",
    "            stat[table][food] += 1\n",
    "            all_food.add(food)\n",
    "\n",
    "        all_food = sorted(all_food)\n",
    "        first = ['Table'] + all_food\n",
    "        ans = [first]\n",
    "        for table in sorted(stat, key=int):\n",
    "            cnt = stat[table]\n",
    "            l = [table] + [str(cnt[f]) for f in all_food]\n",
    "            ans.append(l)\n",
    "        \n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        table, food = dict(), set()\n",
    "        for _, t, f in orders:\n",
    "            food.add(f)\n",
    "            if t not in table:\n",
    "                table[t] = Counter()\n",
    "            table[t][f] += 1\n",
    "        title = [\"Table\"] + sorted(food)\n",
    "        n = len(title)\n",
    "        return [title] + [[k] + [str(table[k][title[i]]) \\\n",
    "        for i in range(1, n)] for k in sorted(table.keys(), key=lambda x: int(x))]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        lis = set(); inds = set(); n = 0 \n",
    "        for _, ind, food in orders:\n",
    "            if food not in lis:\n",
    "                lis.add(food)\n",
    "            if ind not in inds:\n",
    "                inds.add(ind)\n",
    "        lis = sorted(list(lis));  inds = sorted(list(inds), key = int) ; dic = dict() ; dic_table = dict()\n",
    "        for i, x in enumerate(lis): dic[x] = i\n",
    "        for i, x in enumerate(inds): dic_table[i] = x\n",
    "        st = defaultdict(lambda: [0] * len(lis))\n",
    "        for _, ind, food in orders:\n",
    "            st[ind][dic[food]] += 1 \n",
    "        ans = [['Table']+lis] + [([dic_table[i]]+st[dic_table[i]]) for i in range(len(inds))]\n",
    "        for i,x in enumerate(ans):\n",
    "            for j,xx in enumerate(x):  ans[i][j] = str(xx)\n",
    "        return ans\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import defaultdict\n",
    "#defaultdict可以在dict中查找不存在的key而不报错，不存在时返回默认值。\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "      ans = []\n",
    "      foods = set() #单个食物会多次出现，使用集合存储食物\n",
    "      table_info = defaultdict(lambda: defaultdict(int))  #嵌套的字典，类似于二维的数组\n",
    "\n",
    "      for _,table,food in orders:\n",
    "        table_info[table][food] += 1  #同桌子的同菜品自增1\n",
    "        foods.add(food)\n",
    "\n",
    "      foods = sorted(foods)\n",
    "\n",
    "      ans.append(['Table'] + foods)\n",
    "      for table_num in sorted(table_info, key=lambda x: int(x)):\n",
    "        tmp = [table_num] #变量暂存桌号，后续插入数字\n",
    "\n",
    "        for food in foods:\n",
    "          tmp.append(str(table_info.get(table_num).get(food,0)))\n",
    "\n",
    "        ans.append(tmp)\n",
    "      return ans\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        table_dict = defaultdict(list)\n",
    "        foods = set()\n",
    "        tables = set()\n",
    "        for arr in orders:\n",
    "            _, id, food = arr[0],arr[1],arr[2]\n",
    "            table_dict[id].append(food)\n",
    "            foods.add(food)\n",
    "            tables.add(id)\n",
    "        table_food = {}\n",
    "        for k, v in table_dict.items():\n",
    "            val = Counter(v)\n",
    "            table_food[k] = val\n",
    "        print(table_food)\n",
    "        fooditem = sorted(list(foods))\n",
    "        tableitem = sorted(list(tables), key=lambda x: int(x))\n",
    "        m = len(tables) + 1\n",
    "        n = len(foods) + 1\n",
    "        res = [['']*n for _ in range(m)]\n",
    "        res[0][0] = 'Table'\n",
    "        res[0][1:] = fooditem\n",
    "        for i in range(1,m):\n",
    "            res[i][0] = tableitem[i-1]\n",
    "        for i in range(1,m):\n",
    "            for j in range(1,n):\n",
    "                res[i][j] = str(table_food[res[i][0]][res[0][j]]) \n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        lis = set(); inds = set(); n = 0 \n",
    "        for _, ind, food in orders:\n",
    "            lis.add(food)\n",
    "            inds.add(ind)\n",
    "        lis = sorted(list(lis));  inds = sorted(list(inds), key = int) ; dic = dict() ; dic_table = dict()\n",
    "        for i, x in enumerate(lis): dic[x] = i\n",
    "        for i, x in enumerate(inds): dic_table[i] = x\n",
    "        st = defaultdict(lambda: [0] * len(lis))\n",
    "        for _, ind, food in orders:\n",
    "            st[ind][dic[food]] += 1 \n",
    "        ans = [['Table']+lis] + [([dic_table[i]]+st[dic_table[i]]) for i in range(len(inds))]\n",
    "        for i,x in enumerate(ans):\n",
    "            for j,xx in enumerate(x):  ans[i][j] = str(xx)\n",
    "        return ans\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        ans=[]\n",
    "        meun=set()#记录菜的种类\n",
    "        tables=set()#记录编号\n",
    "        dict_=defaultdict(list)\n",
    "        for i in range(len(orders)):\n",
    "            meun.add(orders[i][2])\n",
    "            dict_[orders[i][1]].append(orders[i][2])\n",
    "            tables.add(orders[i][1])\n",
    "        \n",
    "        tables=sorted(int(item) for item in tables)\n",
    "        meun=sorted(meun)\n",
    "        temp=['Table']\n",
    "        for item in meun:\n",
    "            temp.append(item)\n",
    "        ans.append(temp)\n",
    "\n",
    "        for nu in tables:\n",
    "            temp=[str(nu)]\n",
    "            D=Counter(dict_[str(nu)])\n",
    "            for dishes in meun:\n",
    "                temp.append(str(D[dishes]))\n",
    "            ans.append(temp)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        target = []\n",
    "        l2 = {}\n",
    "        l1 = set()\n",
    "        l3 = []\n",
    "        for i in range (len(orders)):\n",
    "            if orders[i][2] not in l1:\n",
    "                l1.add(orders[i][2])\n",
    "        l1 = list(l1)\n",
    "        l1.sort()\n",
    "        for i in range (len(orders)):\n",
    "            x = l1.index(orders[i][2])\n",
    "            if orders[i][1] not in l2:\n",
    "                l2[orders[i][1]] = [0] * (len(l1) + 1)\n",
    "                l2[orders[i][1]][0] = int(orders[i][1])\n",
    "            l2[orders[i][1]][x + 1] += 1\n",
    "        for key in l2:\n",
    "            l3.append(l2[key])\n",
    "        l3 = sorted(l3, key = lambda x:x[0])\n",
    "        for i in range (len(l3)):\n",
    "            l3[i] = list(map(str, l3[i]))\n",
    "        l1 = [\"Table\"] + l1\n",
    "        l3.insert(0, l1)\n",
    "        return l3\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        lis = set(); inds = set(); n = 0 #n是桌号, 500以内\n",
    "        for _, ind, food in orders:\n",
    "            if food not in lis:\n",
    "                lis.add(food)\n",
    "            if ind not in inds:\n",
    "                n += 1\n",
    "                inds.add(ind)\n",
    "        lis = sorted(list(lis)) #字母排序\n",
    "        inds = sorted(list(inds), key = int) #int type sort\n",
    "        dic = dict()    # food: index\n",
    "        dic_table = dict()\n",
    "        for i, x in enumerate(lis):\n",
    "            dic[x] = i\n",
    "        for i, x in enumerate(inds):\n",
    "            dic_table[i] = x\n",
    "\n",
    "        # ans = [['table']+lis] + [([\"\"]+[''] * len(lis))  for _ in range(n)]\n",
    "        # print(ans,dic, dic_table)\n",
    "        st = defaultdict(lambda: [0] * len(lis))\n",
    "        for _, ind, food in orders:\n",
    "            st[ind][dic[food]] += 1 \n",
    "        ans = [['Table']+lis] + [([dic_table[i]]+st[dic_table[i]]) for i in range(n)]\n",
    "        for i,x in enumerate(ans):\n",
    "            for j,xx in enumerate(x):\n",
    "                ans[i][j] = str(xx)\n",
    "        return ans\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from sortedcontainers import SortedSet, SortedDict\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        all_food = SortedSet()\n",
    "        stat = defaultdict(Counter)\n",
    "        for _, table, food in orders:\n",
    "            stat[table][food] += 1\n",
    "            all_food.add(food)\n",
    "\n",
    "        ans = [['Table'] + list(all_food)]\n",
    "        for table in sorted(stat, key=int):\n",
    "            cnt = stat[table]\n",
    "            l = [table] + [str(cnt[f]) for f in all_food]\n",
    "            ans.append(l)\n",
    "        \n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from sortedcontainers import SortedSet\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        foods = SortedSet()\n",
    "        tables = defaultdict(Counter)\n",
    "        for name, number, food in orders:\n",
    "            foods.add(food)\n",
    "            tables[number][food] += 1\n",
    "        return [[\"Table\"] + [food for food in foods]] + [[table] + [str(tables[table][food]) for food in foods] for table in sorted(tables.keys(), key=int)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        dishes = set()\n",
    "        tables = set()\n",
    "        cnt = collections.Counter()\n",
    "        \n",
    "        for name, table, dish in orders:\n",
    "            tables.add(int(table))\n",
    "            dishes.add(dish)\n",
    "            cnt[(table, dish)] += 1\n",
    "        \n",
    "        dishes = sorted(dishes)\n",
    "        tables = sorted(tables)\n",
    "\n",
    "        result = [[ '0' for _ in range(len(dishes) + 1)] for _ in range(len(tables) + 1)]\n",
    "        result[0][0] = 'Table'\n",
    "\n",
    "        for i in range(1, len(dishes) + 1):\n",
    "            result[0][i] = dishes.pop(0)\n",
    "        \n",
    "        for i in range(1, len(tables) + 1):\n",
    "            result[i][0] = str(tables.pop(0))\n",
    "        \n",
    "        for i in range(1, len(result)):\n",
    "            for j in range(1, len(result[0])):\n",
    "                table_num = result[i][0]\n",
    "                dish_name = result[0][j]\n",
    "                result[i][j] = str(cnt[(table_num, dish_name)])\n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import Counter\n",
    "class Solution:\n",
    "    def displayTable(self, orders):\n",
    "        dishes = set()\n",
    "        tables = set()\n",
    "        # 设置为集合的目的添加桌号和菜名无重复\n",
    "        c = Counter()\n",
    "        # Counter（计数器）：用于追踪值的出现次数\n",
    "        # Counter类继承dict类，所以它能使用dict类里面的方法\n",
    "        # 数据准备\n",
    "        for name, table, dish in orders:\n",
    "            # 转成int为了排序方便\n",
    "            tables.add(int(table))  #获取桌号\n",
    "            dishes.add(dish)  # 获取已点菜名\n",
    "            c[(table, dish)] += 1    # 获取每道菜对应的桌号\n",
    "\n",
    "        # 按照题目要求的排序(对菜品和桌号排序)\n",
    "        dishes = sorted(dishes)\n",
    "        tables = sorted(tables)\n",
    "        result = [[ '0' for _ in range(len(dishes) + 1)] for _ in range(len(tables) + 1)]\n",
    "        # 用来存放结果（菜名和座号），+1 是因为首行和首列\n",
    "        result[0][0] = 'Table'\n",
    "\n",
    "        # 填写第一行菜名（第一列桌号已有安排）\n",
    "        for i in range(1, len(dishes) + 1):\n",
    "            result[0][i] = dishes.pop(0)\n",
    "\n",
    "        # 填第一列\n",
    "        for i in range(1, len(tables) + 1):\n",
    "            result[i][0] = str(tables.pop(0))\n",
    "\n",
    "        # 填 table - dish 出现次数结果\n",
    "        for i in range(1, len(result)):\n",
    "            for j in range(1, len(result[0])):\n",
    "                table_num = result[i][0]\n",
    "                dish_name = result[0][j]\n",
    "                result[i][j] = str(c[(table_num, dish_name)])\n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        s_order, s_table = set(), set()\n",
    "        d = collections.Counter()\n",
    "        for _, table, order in orders:\n",
    "            s_order.add(order)\n",
    "            s_table.add(table)\n",
    "            d[table, order] += 1\n",
    "        s_order = sorted(s_order)\n",
    "        res = [['Table']+s_order]\n",
    "        for i in sorted(s_table, key=int):\n",
    "            res.append([i])\n",
    "            for j in s_order: res[-1].append(str(d[i, j]))\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        s = set()\n",
    "        n = set()\n",
    "        for i in orders:\n",
    "            s.add(i[2])\n",
    "            n.add(int(i[1]))\n",
    "        s = sorted(list(s))\n",
    "        n = sorted(list(n))\n",
    "        d = {}\n",
    "        for i in n:\n",
    "            d[i] = {}\n",
    "            for j in s:\n",
    "                d[i][j] = 0\n",
    "        for i in orders:\n",
    "            d[int(i[1])][i[2]] += 1\n",
    "        t = [\"Table\"]\n",
    "        t.extend(s)\n",
    "        ans = [t]\n",
    "        for i in d:\n",
    "            t = [str(i)]\n",
    "            for j in d[i]:\n",
    "                t.append(str(d[i][j]))\n",
    "            ans.append(t)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        fs = set()\n",
    "        g = dict()\n",
    "        for _, t, f in orders:\n",
    "            if t not in g:\n",
    "                g[t] = defaultdict(int)\n",
    "            g[t][f] += 1\n",
    "            fs.add(f)\n",
    "        fs = sorted(list(fs))\n",
    "        ts = sorted([int(v) for v in g.keys()])\n",
    "        ans = [[\"Table\"] + fs]\n",
    "        for t in ts:\n",
    "            r = [str(t)]\n",
    "            for f in fs:\n",
    "                r.append(str(g[str(t)][f]))\n",
    "            ans.append(r)\n",
    "        return ans\n",
    "            \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        # 哈希表\n",
    "        ans = []\n",
    "        # 构造哈希表 桌号 ：{餐品 ：个数}\n",
    "        tm = defaultdict(lambda: defaultdict(int))\n",
    "        # 餐品\n",
    "        foodList = set()\n",
    "        # 统计每桌的点餐情况与餐品种类\n",
    "        for _, t, f in orders:\n",
    "            tableNum = int(t)\n",
    "            foodList.add(f)\n",
    "            tm[tableNum][f] += 1\n",
    "\n",
    "        # 构造 title\n",
    "        foods = sorted(foodList)   # 按照菜品名字升序排序\n",
    "        title = []\n",
    "        title.append(\"Table\")\n",
    "        title += foods\n",
    "        ans.append(title)   # 加入 title\n",
    "        # 构造 桌号 + 点单内容\n",
    "        for tableNum in sorted(tm.keys()):  # 按照桌号升序排序\n",
    "            cur = []\n",
    "            cur.append(str(tableNum))\n",
    "            for food in foods:\n",
    "                cur.append(str(tm[tableNum][food]))\n",
    "            ans.append(cur)\n",
    "        \n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        ans = []\n",
    "        tm = defaultdict(lambda:defaultdict(int))\n",
    "        ts = set()\n",
    "        for c, t, f in orders:\n",
    "            tidx = int(t)\n",
    "            ts.add(f)\n",
    "            tm[tidx][f] +=1\n",
    "        n, m = len(tm) + 1, len(ts) + 1\n",
    "        foods = sorted(ts)\n",
    "        title = []\n",
    "        title.append(\"Table\")\n",
    "        title += foods\n",
    "        ans.append(title)\n",
    "        for tidx in sorted(tm.keys()):\n",
    "            cur = []\n",
    "            cur.append(str(tidx))\n",
    "            for food in foods:\n",
    "                cur.append(str(tm[tidx][food]))\n",
    "            ans.append(cur)\n",
    "        return ans\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        food_set = set()\n",
    "        table_set = set()\n",
    "        table_food_count = defaultdict(lambda: defaultdict(int))\n",
    "        \n",
    "        # 提取所有食品名称和桌号，同时计算每个桌子上每种食品的数量\n",
    "        for _, table, food in orders:\n",
    "            food_set.add(food)\n",
    "            table_set.add(table)\n",
    "            table_food_count[table][food] += 1\n",
    "            \n",
    "        # 对食品名称和桌号进行排序\n",
    "        foods = sorted(list(food_set))\n",
    "        tables = sorted(list(table_set), key=int)  # 按照数字排序而不是字符串\n",
    "        \n",
    "        # 初始化结果\n",
    "        result = [[\"Table\"] + foods]\n",
    "        \n",
    "        # 添加每个桌子的数据\n",
    "        for table in tables:\n",
    "            row = [table]\n",
    "            for food in foods:\n",
    "                row.append(str(table_food_count[table][food]))  # 转换为字符串\n",
    "            result.append(row)\n",
    "        \n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        \n",
    "        \n",
    "        \n",
    "        # my solution ... 412 ms ... 64 % ... 48.4 MB ... 22 %\n",
    "        #  time: O(nlogn)\n",
    "        # space: O(n)\n",
    "        \n",
    "        mapp = {}\n",
    "        pool = set()\n",
    "        for _, index, food in orders:\n",
    "            if index not in mapp:\n",
    "                mapp[index] = collections.defaultdict(int)\n",
    "            mapp[index][food] += 1\n",
    "            pool.add(food)\n",
    "        res = [['Table'] + sorted(pool)]\n",
    "        for index in sorted(mapp.keys(), key = lambda x: int(x)):\n",
    "            res.append([str(index)])\n",
    "            for food in res[0][1:]:\n",
    "                res[-1].append(str(mapp[index][food]))\n",
    "        return res\n",
    "        \n",
    "        \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        res = []\n",
    "        tm = defaultdict(lambda: defaultdict(int))\n",
    "        ts = set()\n",
    "        for c, t, f in orders:\n",
    "            tidx = int(t)\n",
    "            ts.add(f)\n",
    "            tm[tidx][f] += 1\n",
    "        foods = sorted(ts)\n",
    "        title = []\n",
    "        title.append('Table')\n",
    "        title += foods\n",
    "        res.append(title)\n",
    "        for tidx in sorted(tm.keys()):\n",
    "            cur = []\n",
    "            cur.append(str(tidx))\n",
    "            for food in foods:\n",
    "                cur.append(str(tm[tidx][food]))\n",
    "            res.append(cur)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        ans = []\n",
    "        # 桌号 : {餐品 : 个数}（用于构造内容）\n",
    "        tm = defaultdict(lambda: defaultdict(int))\n",
    "        # 餐品（用于构造 title）\n",
    "        ts = set()\n",
    "        for c,t,f in orders:\n",
    "            tidx = int(t)\n",
    "            ts.add(f)\n",
    "            tm[tidx][f] += 1\n",
    "        n, m = len(tm) + 1, len(ts) + 1\n",
    "        # 构造 title & 手动排序\n",
    "        foods = sorted(ts)\n",
    "        title = []\n",
    "        title.append(\"Table\")\n",
    "        title += foods\n",
    "        ans.append(title)\n",
    "        # 构造内容 & 手动排序\n",
    "        for tidx in sorted(tm.keys()):\n",
    "            cur = []\n",
    "            cur.append(str(tidx))\n",
    "            for food in foods:\n",
    "                cur.append(str(tm[tidx][food]))\n",
    "            ans.append(cur)\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        st = defaultdict(lambda: defaultdict(int))  ##直接字典套字典\n",
    "        foods = set()\n",
    "        for _, ind, food in orders:\n",
    "            st[int(ind)][food] += 1\n",
    "            if food not in foods:\n",
    "                foods.add(food)\n",
    "        ans = [['Table']+sorted(list(foods))]\n",
    "        for ind in sorted(st):  #直接返回sorted(st.keys())\n",
    "            ans += [[str(ind)]+ [str(st[ind][f]) for f in ans[0][1:]]]\n",
    "        return ans\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        ans = []\n",
    "        tm = defaultdict(lambda: defaultdict(int))\n",
    "        ts = set()\n",
    "        for c, t, f in orders:\n",
    "            tidx = int(t)\n",
    "            ts.add(f)\n",
    "            tm[tidx][f] += 1\n",
    "        n, m = len(tm) + 1, len(ts) + 1\n",
    "        foods = sorted(ts)\n",
    "        title = []\n",
    "        title.append(\"Table\")\n",
    "        title += foods\n",
    "        ans.append(title)\n",
    "        for tidx in sorted(tm.keys()):\n",
    "            cur = []\n",
    "            cur.append(str(tidx))\n",
    "            for f in foods:\n",
    "                cur.append(str(tm[tidx][f]))\n",
    "            ans.append(cur)\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        st = defaultdict(lambda: defaultdict(int))  ##直接字典套字典\n",
    "        foods = set()\n",
    "        for _, ind, food in orders:\n",
    "            st[int(ind)][food] += 1\n",
    "            foods.add(food)\n",
    "        ans = [['Table']+sorted(list(foods))]\n",
    "        for ind in sorted(st):  #直接返回sorted(st.keys())\n",
    "            ans += [[str(ind)]+ [str(st[ind][f]) for f in ans[0][1:]]]\n",
    "        return ans\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from collections import defaultdict\n",
    "from typing import List\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        food_set = set()\n",
    "        table_set = set()\n",
    "        table_food_count = defaultdict(lambda: defaultdict(int))\n",
    "        \n",
    "        # 提取所有食品名称和桌号，同时计算每个桌子上每种食品的数量\n",
    "        for _, table, food in orders:\n",
    "            food_set.add(food)\n",
    "            table_set.add(table)\n",
    "            table_food_count[table][food] += 1\n",
    "            \n",
    "        # 对食品名称和桌号进行排序\n",
    "        foods = sorted(list(food_set))\n",
    "        tables = sorted(list(table_set), key=int)  # 按照数字排序而不是字符串\n",
    "        \n",
    "        # 初始化结果\n",
    "        result = [[\"Table\"] + foods]\n",
    "        \n",
    "        # 添加每个桌子的数据\n",
    "        for table in tables:\n",
    "            row = [table]\n",
    "            for food in foods:\n",
    "                row.append(str(table_food_count[table][food]))  # 转换为字符串\n",
    "            result.append(row)\n",
    "        \n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n",
    "        st = defaultdict(lambda: defaultdict(int))  ##直接字典套字典\n",
    "        foods = set()\n",
    "        for _, ind, food in orders:\n",
    "            st[int(ind)][food] += 1\n",
    "            foods.add(food)\n",
    "        ans = [['Table']+sorted(list(foods))]\n",
    "        for ind in sorted(st):  #直接返回sorted(st.keys())\n",
    "            ans += [[str(ind)]+ [str(st[ind][f]) for f in ans[0][1:]]]\n",
    "        return ans\n",
    "\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
